package com.idealighter.game.roomcard.manager;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.idealighter.game.event.manager.EventMgr;
import com.idealighter.game.player.struct.Player;
import com.idealighter.game.roomcard.common.AbstractRoomCardRoom;
import com.idealighter.game.schedule.manager.ScheduleMgr;
import com.idealighter.game.server.db.datadb.generate.domain.RoomCardGroupMemberDomain;
import com.idealighter.game.server.db.datadb.generate.domain.RoomCardGroupMemberDomainExample;
import com.idealighter.game.server.db.datadb.mapper.RoomCardGroupMemberMapper;
import com.idealighter.utils.check.EmptyUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Singleton
public class RoomCardRoomListMgrScript {
  // 房间列表数据库操作
  // private RoomCardRoomListMapper roomCardRoomListMapper;
  // @Inject
  // private ExecutorMgr executorMgr;
  private static final Logger LOG = LoggerFactory.getLogger(RoomCardRoomListMgrScript.class);
  // // 所有可加入|正在进行的房卡
  private Map<Long, AbstractRoomCardRoom> allRoomMap = new ConcurrentHashMap<>();
  private RoomCardGroupMemberMapper roomCardGroupMemberMapper;

  /**
   * 构造函数.
   */
  @Inject
  public RoomCardRoomListMgrScript(// RoomCardRoomListMapper roomCardRoomListMapper,
      RoomCardGroupMemberMapper roomCardGroupMemberMapper, ScheduleMgr scheduleMgr,
      EventMgr eventMgr) {
    // this.roomCardRoomListMapper = roomCardRoomListMapper;
    this.roomCardGroupMemberMapper = roomCardGroupMemberMapper;
    eventMgr.register(this);
  }

  /**
   * @Title addRoomCard.
   * @Description 添加到房卡
   * @date 2018年5月21日 下午1:56:01
   * @param room .
   */
  public void addRoomCard(AbstractRoomCardRoom room) {
    allRoomMap.put(room.getId(), room);
    LOG.info("RoomCardRoomListMgrScript添加房卡[{}][{}]", room.game().getDesc(), room.getId());
  }

  /**
   * @Title removeRoomCard.
   * @Description 移除房间
   * @date 2018年6月8日 下午3:40:28
   * @param roomId .
   */
  public void removeRoomCard(Long roomId) {
    AbstractRoomCardRoom room = allRoomMap.remove(roomId);

    if (room != null) {
      LOG.info("RoomCardRoomListMgrScript移除房卡[{}][{}]", room.game().getDesc(), roomId);
    }
  }

  public AbstractRoomCardRoom findRoomCard(long roomId) {
    return allRoomMap.get(roomId);
  }

  /**
   * @Title findRoomCardList.
   * @Description 获取房卡列表
   * @return .
   */
  public List<AbstractRoomCardRoom> findRoomCardList(Player player, int type, long lastRoomId,
      int groupId, int pageSize) {
    List<AbstractRoomCardRoom> resultList = new ArrayList<>();

    List<AbstractRoomCardRoom> allList = new ArrayList<>(allRoomMap.values());
    Long playerId = player.playerBo().getId();
    Collections.sort(allList, (a, b) -> (int) (b.getId() - a.getId()));
    // 玩家所在群
    List<Integer> groupIds = findMemberGroupIds(player.getId());
    for (AbstractRoomCardRoom room : allList) {
      // 如果
      if (room.hasPlayer(playerId) // 玩家加入的
          || (groupIds != null && groupIds.contains(room.getGroupId())) // 玩家家如的群
          || room.getOwnerId().equals(playerId)) {
        if (lastRoomId > 0) {
          if (room.getId() >= lastRoomId) {
            continue;
          }
        }
        if (resultList.size() >= pageSize) {
          break;
        }
        int group = room.getGroupId();
        if (type == 0) { // 好友场
          if (group == 0) {
            resultList.add(room);
          }
        } else if (type == 1) { // 牛友场
          if (group > 0) {
            resultList.add(room);
          }
        } else if (type == 2) { // 牛友群
          if (group == groupId) {
            resultList.add(room);
          }
        }
      }
    }
    return resultList;
  }

  private List<RoomCardGroupMemberDomain> findMemberGroups(long playerId) {
    RoomCardGroupMemberDomainExample example = new RoomCardGroupMemberDomainExample();
    example.createCriteria().andPlayerIdEqualTo(playerId);
    example.setOrderByClause("id desc");
    return roomCardGroupMemberMapper.selectByExample(example);
  }

  private List<Integer> findMemberGroupIds(long playerId) {
    List<Integer> result = null;
    List<RoomCardGroupMemberDomain> groupList = findMemberGroups(playerId);
    if (EmptyUtil.listIsNotEmpty(groupList)) {
      result = new ArrayList<Integer>();
      for (RoomCardGroupMemberDomain item : groupList) {
        result.add(item.getGroupId());
      }
    }
    return result;
  }


  //
  // /**
  // * @Title findRoomCardRoomListById.
  // * @Description 获取
  // * @author houdongsheng
  // * @date 2018年5月2日 下午5:48:08
  // * @param id
  // * @return
  // */
  // @SuppressWarnings("unchecked")
  // public RoomCardRoomCfg<? extends RoomCardRoomCfgValue> findRoomCardRoomListById(Long id) {
  // RoomCardRoomListDomain record = roomCardRoomListDomainMapper.selectByPrimaryKey(id);
  // return RoomCardRoomListConvert.INSTANCE.po2bo(record);
  // }
  //
  // /**
  // * @Title minusLeftGame.
  // * @Description 扣除剩余游戏场次
  // * @author houdongsheng
  // * @date 2018年5月4日 下午5:34:21
  // * @param id
  // * @param gameId
  // * @param round
  // */
  // public void minusLeftGame(Long id, int gameId, int round) {
  // executorMgr.getRoomCardExecutor(gameId).execute(() -> {
  // RoomCardRoomCfg<? extends RoomCardRoomCfgValue> roomCard = roomListMap.get(id);
  // if (roomCard != null) {
  // int leftGame = roomCard.getLeftGame() - round;
  // if (leftGame < 0) {
  // leftGame = 0;
  // }
  // roomCard.setLeftGame(leftGame);
  // if (leftGame <= 0) {
  // roomCardOver(roomCard);
  // } else {
  // // 更新数据库中的房间状态
  // updateDomain(roomCard);
  // }
  // }
  // });
  // }
  //
  // /**
  // * @Title minusLeftTime.
  // * @Description 扣除剩余时间
  // * @author houdongsheng
  // * @date 2018年5月4日 下午5:35:00
  // * @param id
  // * @param gameId
  // * @param time
  // */
  // public void minusLeftTime(Long id, int gameId, long time) {
  // executorMgr.getRoomCardExecutor(gameId).execute(() -> {
  // RoomCardRoomCfg<? extends RoomCardRoomCfgValue> roomCard = findRoomCardRoomListById(id);
  // if (roomCard != null && roomCard.getState().equals(RoomCardStateConstant.GOING)
  // && roomCard.getBillType().equals(RoomCardBillTypeConstant.BY_TIME)) {
  // long leftTime = roomCard.getLeftTime() - time;
  // if (leftTime < 0L) {
  // leftTime = 0;
  // }
  // roomCard.setLeftTime(leftTime);
  // if (leftTime <= 0L) {
  // roomCardOver(roomCard);
  // } else {
  // // 更新数据库中的房间状态
  // updateDomain(roomCard);
  // }
  // }
  // });
  // }
  //
  // /**
  // * @Title roomCardOver.
  // * @Description 正常结束
  // * @author houdongsheng
  // * @date 2018年5月4日 下午9:31:40
  // * @param roomCard
  // */
  // private void roomCardOver(RoomCardRoomCfg<? extends RoomCardRoomCfgValue> roomCard) {
  // // 游戏结束
  // roomCard.setState(RoomCardStateConstant.OVER);
  // // 触发房卡超时事件
  //
  // // 移除
  // roomListMap.remove(roomCard.getId());
  //
  // // 添加日志
  //
  // // 更新数据库中的房间状态
  // updateDomain(roomCard);
  // }
  //
  // /**
  // * @Title roomCardAdminClose.
  // * @Description 管理员关闭
  // * @author houdongsheng
  // * @date 2018年5月4日 下午9:31:24
  // * @param roomCard
  // */
  // private void roomCardAdminClose(RoomCardRoomCfg<? extends RoomCardRoomCfgValue> roomCard) {
  // // 游戏结束
  // roomCard.setState(RoomCardStateConstant.CLOSED_BY_ADMIN);
  // // 触发房卡被管理员关闭事件
  //
  // // 移除
  // roomListMap.remove(roomCard.getId());
  //
  // // 添加日志
  //
  // // 更新数据库中的房间状态
  // updateDomain(roomCard);
  // }
  //
  // /**
  // * @Title roomCardRemoveByOwner.
  // * @Description 玩家移除房卡(已经结束的房卡)
  // * @author houdongsheng
  // * @date 2018年5月4日 下午9:39:34
  // * @param roomCard
  // */
  // private void roomCardRemoveByOwner(long roomId) {
  // if (!roomListMap.containsKey(roomId)) {
  // removeDomain(roomId);
  // }
  // }
  //
  //
  //
  // /**
  // * @Title rechargeGame.
  // * @Description 充值场次
  // * @author houdongsheng
  // * @date 2018年5月4日 下午5:35:12
  // * @param id
  // * @param gameId
  // * @param fee
  // * @param round
  // */
  // public void rechargeGame(Long id, int gameId, long fee, int round) {
  // executorMgr.getRoomCardExecutor(gameId).execute(() -> {
  // RoomCardRoomCfg<? extends RoomCardRoomCfgValue> roomCard = findRoomCardRoomListById(id);
  // if (roomCard != null && roomCard.getState().equals(RoomCardStateConstant.GOING)
  // && roomCard.getBillType().equals(RoomCardBillTypeConstant.BY_GAME)) {
  // int leftGame = roomCard.getLeftGame() + round;
  // roomCard.setLeftGame(leftGame);
  // roomCard.setRechargeFee(roomCard.getRechargeFee() + fee);
  // // 更新数据库
  // // 添加日志
  // }
  // });
  //
  // }
  //
  // /**
  // * @Title rechargeTime.
  // * @Description 充值时间
  // * @author houdongsheng
  // * @date 2018年5月4日 下午5:35:27
  // * @param id
  // * @param gameId
  // * @param fee
  // * @param time
  // */
  // public void rechargeTime(Long id, int gameId, long fee, long time) {
  // executorMgr.getRoomCardExecutor(gameId).execute(() -> {
  // RoomCardRoomCfg<? extends RoomCardRoomCfgValue> roomCard = findRoomCardRoomListById(id);
  // if (roomCard != null && roomCard.getState().equals(RoomCardStateConstant.GOING)
  // && roomCard.getBillType().equals(RoomCardBillTypeConstant.BY_TIME)) {
  // long leftTime = roomCard.getLeftTime() + time;
  // roomCard.setLeftTime(leftTime);
  // roomCard.setRechargeFee(roomCard.getRechargeFee() + fee);
  // // 更新数据库
  // // 添加日志
  // }
  // });
  // }
  //
  // private void updateDomain(RoomCardRoomCfg<? extends RoomCardRoomCfgValue> cfg) {
  // RoomCardRoomListDomain record = RoomCardRoomListConvert.INSTANCE.bo2po(cfg);
  // roomCardRoomListDomainMapper.updateByPrimaryKeyWithBLOBs(record);
  // }
  //
  // private void addDomain(RoomCardRoomCfg<? extends RoomCardRoomCfgValue> cfg) {
  // RoomCardRoomListDomain record = RoomCardRoomListConvert.INSTANCE.bo2po(cfg);
  // roomCardRoomListDomainMapper.insertSelective(record);
  // }
  //
  // private void removeDomain(Long id) {
  // RoomCardRoomListDomain record = new RoomCardRoomListDomain();
  // record.setId(id);
  // record.setRemove((byte) 1);
  // roomCardRoomListDomainMapper.updateByPrimaryKeySelective(record);
  // }
}
